<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
    public function index(){
        $recaptcha_config = C("recaptcha");
        $siteKey = $recaptcha_config['siteKey'];
        $this->assign("siteKey",$siteKey);

        $typelist = M('type')->select();
        $this->assign("typelist", $typelist);
        $this->display('Web/index');
    }


    public function  getItemList($type){

        $itemlist = M('itemlist')->where('type = "'.$type.'"')->order('lasttime desc')->select();

        foreach ($itemlist as &$item)
        {
            $item['nickname']=$this->getUserNameById($item['author']);
        }
        $this->assign('itemlist',$itemlist);
        $this->assign('type',$type);
        $this->display('Web/left_artcle_list');
    }




    public function getUserNameById($id){
        $user = M('userinfo')->where('id = "'.$id.'"')->find();
        if ($user) {
            return $user['nickname'];
        }else{
            return "游客";
        }
    }

    /**
     * 发布新的帖子
     */
    public function addItem(){

        $title = $_POST['title'];
        $type = $_POST['type'];
        $this->checkLogin();
        $itemlist['title'] = $title;
        $itemlist['time'] = time();
        $itemlist['author'] = $_SESSION['USER']['id'];
        $itemlist['creply'] = 0;
        $itemlist['cgood'] = 0;
        $itemlist['cbad'] = 0;
        $itemlist['type'] = $type;
        $itemlist['lasttime']=  time();
        $itemid = M('itemlist')->add($itemlist);

        if($itemid){
            $item['number']=0; //暂时设置为0
            $item['userid'] = $itemlist['author'];
            $item['time'] = $itemlist['time'];
            $item['content'] = $_POST['myContent'];
            $item['itemid']=$itemid;
            M('items')->add($item);
        }

        $this->ajaxReturn(array('status'=>1));
    }

    /**得到贴子列表
     * @param $id
     */
    public function getItems($id){
        $recaptcha_config = C("recaptcha");
        $siteKey = $recaptcha_config['siteKey'];
        $this->assign("siteKey",$siteKey);
        
        $items = M('items')->where('itemid = "'.$id.'"')->select();

        foreach ($items as &$item)
        {
            $item['nickname']=$this->getUserNameById($item['userid']);
        }
        $this->assign('items',$items);
        $this->display('Web/main_page_container');
    }

    /**回复帖子
     * @param $id
     */
    public function replayItems($id){
        $item['number']=0; //暂时设置为0
        if(is_null($_SESSION["USER"]))
        {
            $item['userid']=-1;
        }else {
            $item['userid'] = $_SESSION['USER']['id'];
        }
        $item['time'] = time();
        $item['content'] = $_POST['myContent'];
        $item['itemid']=$id;
        M('items')->add($item);

        $itemlist = M('itemlist')->where('id="'.$id.'"')->find();
        $itemlist['creply']= $itemlist['creply']+1;
        $itemlist['lasttime']= time();
        M('itemlist')->save($itemlist);

//        $this->redirect('/Index/getItems/id/'.$id);
        $this->ajaxReturn(array('status'=>1));
    }

    public function CGood(){
        $id = $_POST['id'];
        if (is_null($_SESSION['USER'])){
            return $this->ajaxReturn(array('status'=>3));
        }
        $goods = M('goods')->where('itemid="'.$id.'" and userid = "'.$_SESSION['USER']['id'].'"')->find();
        if (is_null($goods))
        {
            $data_good['itemid']=$id;
            $data_good['userid']=$_SESSION['USER']['id'];
            M('goods')->add($data_good);

            $data_bad=M('bads')->where('itemid="'.$id.'" and userid = "'.$_SESSION['USER']['id'].'"')->find();

            $itemlist = M('itemlist')->where('id="'.$id.'"')->find();
            $itemlist['cgood']= $itemlist['cgood']+1;
            if(!is_null($data_bad)){
                $itemlist['cbad']= $itemlist['cbad']-1;
            }
             M('itemlist')->save($itemlist);

            M('bads')->delete($data_bad['id']);
            $itemlist = M('itemlist')->where('id="'.$id.'"')->find();
            return $this->ajaxReturn(array('status'=>1,'goodsnum'=>$itemlist['cgood'],'badnum'=>$itemlist['cbad']));
        }else{
            return $this->ajaxReturn(array('status'=>2));
        }
    }


    public function CBad(){
        $id = $_POST['id'];
        if (is_null($_SESSION['USER'])){
            return $this->ajaxReturn(array('status'=>3));
        }

        $bads = M('bads')->where('itemid="'.$id.'" and userid = "'.$_SESSION['USER']['id'].'"')->find();


        if (is_null($bads))
        {
            $data_bad['itemid']=$id;
            $data_bad['userid']=$_SESSION['USER']['id'];

            M('bads')->add($data_bad);

            $data_good=M('goods')->where('itemid="'.$id.'" and userid = "'.$_SESSION['USER']['id'].'"')->find();

            $itemlist = M('itemlist')->where('id="'.$id.'"')->find();
            $itemlist['cbad']= $itemlist['cbad']+1;

            if(!is_null($data_good)){
                $itemlist['cgood']= $itemlist['cgood']-1;
            }

            M('itemlist')->save($itemlist);
            M('goods')->delete($data_good['id']);
            $itemlist = M('itemlist')->where('id="'.$id.'"')->find();
            return $this->ajaxReturn(array('status'=>1,'goodsnum'=>$itemlist['cgood'],'badnum'=>$itemlist['cbad']));
        }else{
            return $this->ajaxReturn(array('status'=>2));
        }
    }


    public function changnickname(){
        $name = $_POST['name'];

        $this->checkLogin();
        if (is_null($_SESSION['USER'])) {
            $this->ajaxReturn(array('status'=>2));
        }else{
            $id = $_SESSION['USER']['id'];
        }

        $user = M('userinfo')->where('id = "'.$id.'"')->find();
        $user['nickname']=$name;
        M('userinfo')->save($user);
        $_SESSION['USER']['nickname']=$name;
        $this->ajaxReturn(array('status'=>1,'nickname'=>$name));

    }

    public function changpwd(){
        $opwd = $_POST['oldpwd'];
        $npwd = $_POST['newpwd'];
        if (is_null($_SESSION['USER'])) {
            $this->ajaxReturn(array('status'=>2));
        }else{
            $id = $_SESSION['USER']['id'];
        }
        $user = M('userinfo')->where('id = "'.$id.'"')->find();
        if ($user['password']==md5($opwd)){
            $user['password']=md5($npwd);
            M('userinfo')->save($user);
            $this->ajaxReturn(array('status'=>1));
        }else{
            $this->ajaxReturn(array('status'=>0));
        }
    }


    public function logout()
    {
        $_SESSION['USER'] = null;
        $this->redirect("/Index/index");
    }


    public function test(){
        $this->display('Test/index');
    }


    public function checkLogin(){
        if (is_null($_SESSION["USER"])) {
           $this->redirect("/Index/index");
        }
    }

    public function checking()
    {
        $usernaem=$_POST['username'];
        $password = $_POST['password'];
        $result = M("userinfo")->where("username='" .$usernaem."'")->find();
        if($result)
        {
            if($result['password']==md5($password)) {
                if ($result['type'] == 1) {
                    $_SESSION["USER"] = $result;
                    $this->success("登陆成功", U('Index/index'));
                }else{
                    $this->error('请先登录邮箱验证',U('index/index'));
                }
            }else
            {
                $this->error('账号密码错误',U('Index/index'));
            }
        }
        else {
            $this->error('账号密码错误', U('Index/index'));
        }
    }




    public function save_info(){
        $ueditor_config = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents("./Public/Web/Ueditor/php/config.json")), true);
        $action = $_GET['action'];
        switch ($action) {
            case 'config':
                $result = json_encode($ueditor_config);
                break;
            /* 上传图片 */
            case 'uploadimage':
                /* 上传涂鸦 */
            case 'uploadscrawl':
                /* 上传视频 */
            case 'uploadvideo':
                /* 上传文件 */
            case 'uploadfile':
                $upload = new \Think\Upload();
                $upload->maxSize = 3145728;
                $upload->rootPath = './Public/Uploads/';
                $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
                $info = $upload->upload();
                if (!$info) {
                    $result = json_encode(array(
                        'state' => $upload->getError(),
                    ));
                } else {
                    $url = __ROOT__ . "/Public/Uploads/" . $info["upfile"]["savepath"] . $info["upfile"]['savename'];
                    $result = json_encode(array(
                        'url' => $url,
                        'title' => htmlspecialchars($_POST['pictitle'], ENT_QUOTES),
                        'original' => $info["upfile"]['name'],
                        'state' => 'SUCCESS'
                    ));
                }
                break;
            default:
                $result = json_encode(array(
                    'state' => '请求地址出错'
                ));
                break;
        }
        /* 输出结果 */
        if (isset($_GET["callback"])) {
            if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
                echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
            } else {
                echo json_encode(array(
                    'state' => 'callback参数不合法'
                ));
            }
        } else {
            echo $result;
        }
    }

    public function referenceItem($id){
        $item = M('items')->where('id = "'.$id.'"')->find();
        $count = M('items')->where('itemid = "'.$item['itemid'].'" and id <= '.$id)->count();
        $content = "引用: #".$count." ".$this->getUserNameById($item['userid']).' 内容<br>'.$item['content'].'<br>';
        $this->ajaxReturn(array('status'=>1,'content'=>$content,'id'=>$id));
    }




}